package com.kepler.social.web.configuration;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchClientConfig {


    /**
     * 不这样写，底下得代码会报错
     * ElasticsearchClientConfigurations.java
     *        @ConditionalOnMissingBean(ElasticsearchTransport.class)
     *    static class ElasticsearchTransportConfiguration {
     *
     *        @Bean
     *        RestClientTransport restClientTransport(RestClient restClient, JsonpMapper jsonMapper,
     * 				ObjectProvider<TransportOptions> transportOptions) {
     * 			return new RestClientTransport(restClient, jsonMapper, transportOptions.getIfAvailable());
     *        }
     *
     *    }
     * @return
     */
    @Bean
    RestClientTransport restClientTransport() {
        RestClient client = RestClient.builder(new HttpHost("localhost", 9200, "http")).build();
        return new RestClientTransport(client, new JacksonJsonpMapper());
    }

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        return new ElasticsearchClient(restClientTransport());
    }

//    private HttpHost[] toHttpHost() {
////        if (StringUtils.isEmpty(hosts)) {
////            throw new RuntimeException("invalid elasticsearch configuration");
////        }
//
//        String[] hostArray = "http://localhost:9200/".split(",");
//        HttpHost[] httpHosts = new HttpHost[hostArray.length];
//        HttpHost httpHost;
//        for (int i = 0; i < hostArray.length; i++) {
//            String[] strings = hostArray[i].split(":");
//            httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "http");
//            httpHosts[i] = httpHost;
//        }
//        return httpHosts;
//    }


//    @Bean
//    public ElasticsearchClient elasticsearchClient() {
//        HttpHost[] httpHosts = toHttpHost();
//        RestClient restClient = RestClient.builder(httpHosts).build();
//        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
//        return new ElasticsearchClient(transport);
//    }
//
//    @Bean
//    public ElasticsearchAsyncClient elasticsearchAsyncClient() {
//        HttpHost[] httpHosts = toHttpHost();
//        RestClient restClient = RestClient.builder(httpHosts).build();
//        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
//        return new ElasticsearchAsyncClient(transport);
//    }


}
